<?php
/**修改权限验证check方法
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/2/7
 * Time: 13:49
 */

namespace App\Services;

use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Auth;

class MyPermission
{

    /**
     * Check permission.
     *
     * @param $permission
     *
     * @return true
     */
    public static function check($permission)
    {
        if (static::isAdministrator()) {
            return true;
        }
        if (is_array($permission)) {
            collect($permission)->each(function ($permission) {
                call_user_func([MyPermission::class, 'check'], $permission);
            });
        }

        if (Auth::guard('admin')->user()->can($permission)) {
            return true;
        }

        if (Auth::guard('admin')->user()->cannot($permission)) {
            //static::error();
            return false;
        }
    }

    /**
     * Roles allowed to access.
     *
     * @param $roles
     *
     * @return true
     */
    public static function allow($roles)
    {
        if (static::isAdministrator()) {
            return true;
        }

        if (!Auth::guard('admin')->user()->inRoles($roles)) {
            //static::error();
            return false;
        }
    }

    /**
     * Roles denied to access.
     *
     * @param $roles
     *
     * @return true
     */
    public static function deny($roles)
    {
        if (static::isAdministrator()) {
            return true;
        }

        if (Auth::guard('admin')->user()->inRoles($roles)) {
            //static::error();
            return false;
        }
    }

    /**
     * Send error response page.
     */
    protected static function error()
    {
        $content = Admin::content(function ($content) {
            $content->body(view('admin::deny'));
        });

        response($content)->send();
        exit;
    }

    /**
     * If current user is administrator.
     *
     * @return mixed
     */
    public static function isAdministrator()
    {
        return Auth::guard('admin')->user()->isRole('administrator');
    }

}